﻿using System;
using System.Windows.Forms;
using OFX.Aggregator.Infrastructure;

namespace OFX.Aggregator.WebScraping.Implementation.BESnet.Checking
{
	public partial class FetchStatementUserControl : UserControl
	{
		private readonly IStatementAction statementAction;
		private readonly StatementSource statementSource;
		private readonly IStatementProcessingWorkflow workflow;
		private Form subscribedParentForm;

		public FetchStatementUserControl(
			StatementSource source, IStatementAction action,
			IStatementProcessingWorkflow workflow)
		{
			this.statementSource = source;
			this.statementAction = action;
			this.workflow = workflow;

			this.InitializeComponent();
		}

		private void UpdateFormState()
		{
			this.buttonFetchStatement.Enabled = this.statementSource.Retrieval.CanRetrieveStatement();
		}

		private void buttonFetchStatement_Click(object sender, EventArgs e)
		{
			this.workflow.PerformWorkflow(this.statementSource, this.statementAction);
		}

		private void BESnetCheckingStatementUserControl_ParentChanged(object sender, EventArgs e)
		{
			if (this.subscribedParentForm != null)
			{
				this.subscribedParentForm.Activated -= this.ParentForm_Activated;
				this.subscribedParentForm = null;
			}

			this.UpdateFormState();

			if (ParentForm != null)
			{
				this.subscribedParentForm = ParentForm;
				this.subscribedParentForm.Activated += this.ParentForm_Activated;
			}
		}

		private void ParentForm_Activated(object sender, EventArgs e)
		{
			this.UpdateFormState();
		}
	}
}